<template>
  <div class="app-detail-container">
    <NavBar />
    
    <!-- 数据导出对话框 -->
    <DataExportDialog
      :visible.sync="showExportDialog"
      :app-id="appId"
      :app-name="appInfo.name"
    />
    
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" icon="el-icon-arrow-left">返回</el-button>
        <h1>{{ appInfo.name || '应用详情' }}</h1>
        <el-tag :type="getStatusType(appInfo.status)">{{ getStatusText(appInfo.status) }}</el-tag>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData" icon="el-icon-refresh">刷新数据</el-button>
        <el-button @click="editApp" icon="el-icon-edit">编辑信息</el-button>
      </div>
    </div>

    <!-- 应用基本信息 -->
    <el-card class="app-info-card">
      <div slot="header" class="card-header">
        <span>应用基本信息</span>
        <el-button type="text" @click="editApp">编辑</el-button>
      </div>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="应用名称">{{ appInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="应用ID">{{ appInfo.id }}</el-descriptions-item>
        <el-descriptions-item label="APP Key">{{ appInfo.appkey }}</el-descriptions-item>
        <el-descriptions-item label="应用包名">{{ appInfo.package_name || '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="应用平台">{{ getPlatformText(appInfo.platform) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(appInfo.created_at) }}</el-descriptions-item>
        <el-descriptions-item label="应用描述" :span="2">{{ appInfo.description || '暂无描述' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 链接生成工具 -->
    <el-card class="link-generator-card">
      <div slot="header" class="card-header">
        <span>推广链接生成</span>
        <el-button type="text" @click="showAdvancedOptions = !showAdvancedOptions">
          {{ showAdvancedOptions ? '收起' : '高级选项' }}
        </el-button>
      </div>
      
      <el-form :model="linkForm" label-width="100px">
        <el-form-item label="落地页类型">
          <el-radio-group v-model="linkForm.landingType">
            <el-radio label="unified">统一落地页</el-radio>
            <el-radio label="custom">自定义落地页</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="自定义参数" v-if="showAdvancedOptions">
          <el-input
            v-model="linkForm.customParams"
            type="textarea"
            :rows="3"
            placeholder="请输入自定义参数，格式：key1=value1&key2=value2"
          ></el-input>
          <div class="form-tip">支持自定义参数传递，将自动附加到生成的链接中</div>
        </el-form-item>
        
        <el-form-item label="渠道标识" v-if="showAdvancedOptions">
          <el-input
            v-model="linkForm.channel"
            placeholder="请输入渠道标识"
          ></el-input>
          <div class="form-tip">用于区分不同的推广渠道</div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="generateLink" icon="el-icon-link">生成推广链接</el-button>
          <el-button @click="resetLinkForm" icon="el-icon-refresh">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 生成的链接展示 -->
      <div v-if="generatedLink" class="generated-link-section">
        <el-divider></el-divider>
        <div class="link-result">
          <div class="link-label">生成的推广链接：</div>
          <div class="link-display">
            <el-input v-model="generatedLink" readonly>
              <template slot="append">
                <el-button @click="copyLink" icon="el-icon-copy-document">复制</el-button>
                <el-button @click="previewLink" icon="el-icon-view">预览</el-button>
                <el-button @click="testLink" icon="el-icon-video-play">测试</el-button>
              </template>
            </el-input>
          </div>
        </div>
        <div class="link-stats" v-if="linkStats">
          <el-alert
            :title="`该链接已使用 ${linkStats.used_count || 0} 次，最近使用：${formatDate(linkStats.last_used_at)}`"
            type="info"
            :closable="false"
          ></el-alert>
        </div>
      </div>
    </el-card>

    <!-- 快捷操作 -->
    <el-card class="quick-actions-card">
      <div slot="header" class="card-header">
        <span>快捷操作</span>
      </div>
      <div class="quick-actions">
        <el-button @click="goToStats" icon="el-icon-data-line">查看统计</el-button>
        <el-button @click="goToTest" icon="el-icon-video-play">开发测试</el-button>
        <el-button @click="showApiKey" icon="el-icon-key">API密钥</el-button>
        <el-button @click="goToConfig" icon="el-icon-setting">应用配置</el-button>
        <el-button @click="exportData" icon="el-icon-download" type="primary">数据导出</el-button>
      </div>
    </el-card>

    <!-- 最近生成的链接 -->
    <el-card class="recent-links-card" v-if="recentLinks.length > 0">
      <div slot="header" class="card-header">
        <span>最近生成的链接</span>
        <el-button type="text" @click="clearRecentLinks">清空</el-button>
      </div>
      <el-table :data="recentLinks" style="width: 100%">
        <el-table-column prop="link" label="链接" show-overflow-tooltip>
          <template slot-scope="scope">
            <a :href="scope.row.link" target="_blank" class="link-text">{{ scope.row.link }}</a>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template slot-scope="scope">
            <el-tag size="small">{{ scope.row.type === 'unified' ? '统一' : '自定义' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="生成时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button size="mini" @click="copyLink(scope.row.link)">复制</el-button>
            <el-button size="mini" type="text" @click="removeRecentLink(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import NavBar from '@/components/NavBarEnhanced.vue'
import DataExportDialog from '@/components/DataExportDialog.vue'
import { getAppDetailApi } from '@/api/apps'
import { formatDate } from '@/utils/date'

export default {
  name: 'AppDetail',
  components: {
    NavBar,
    DataExportDialog
  },
  data() {
    return {
      appId: '',
      appInfo: {},
      loading: false,
      showAdvancedOptions: false,
      showExportDialog: false,
      linkForm: {
        landingType: 'unified',
        customParams: '',
        channel: ''
      },
      generatedLink: '',
      linkStats: null,
      recentLinks: []
    }
  },
  created() {
    this.appId = this.$route.query.id
    if (!this.appId) {
      this.$message.error('应用ID不能为空')
      this.goBack()
      return
    }
    this.loadAppDetail()
    this.loadRecentLinks()
  },
  methods: {
    async loadAppDetail() {
      try {
        this.loading = true
        const res = await getAppDetailApi(this.appId)
        if (res.code !== 200) {
          throw new Error(res.msg || '获取应用详情失败')
        }
        this.appInfo = res.data || {}
      } catch (error) {
        this.$message.error(error.message)
      } finally {
        this.loading = false
      }
    },
    
    loadRecentLinks() {
      // 从本地存储加载最近生成的链接
      const stored = localStorage.getItem(`recent_links_${this.appId}`)
      if (stored) {
        try {
          this.recentLinks = JSON.parse(stored)
        } catch (e) {
          console.error('Failed to load recent links:', e)
        }
      }
    },
    
    saveRecentLink(link, type) {
      const newLink = {
        link,
        type,
        created_at: new Date().toISOString()
      }
      this.recentLinks.unshift(newLink)
      // 只保留最近10条
      if (this.recentLinks.length > 10) {
        this.recentLinks = this.recentLinks.slice(0, 10)
      }
      localStorage.setItem(`recent_links_${this.appId}`, JSON.stringify(this.recentLinks))
    },
    
    generateLink() {
      if (!this.appId) {
        this.$message.error('应用ID不能为空')
        return
      }
      
      try {
        let baseUrl = ''
        if (this.linkForm.landingType === 'custom') {
          baseUrl = `${window.location.origin}/lp/custom/${this.appId}`
        } else {
          baseUrl = `${window.location.origin}/lp/${this.appId}`
        }
        
        const params = new URLSearchParams()
        params.append('ts', Date.now())
        
        // 添加自定义参数
        if (this.linkForm.customParams) {
          try {
            const customParams = new URLSearchParams(this.linkForm.customParams)
            for (const [key, value] of customParams) {
              params.append(key, value)
            }
          } catch (e) {
            this.$message.warning('自定义参数格式不正确，请使用 key=value&key2=value2 格式')
            return
          }
        }
        
        // 添加渠道标识
        if (this.linkForm.channel) {
          params.append('channel', this.linkForm.channel)
        }
        
        this.generatedLink = `${baseUrl}?${params.toString()}`
        this.saveRecentLink(this.generatedLink, this.linkForm.landingType)
        
        this.$message.success('推广链接生成成功！')
        
        // 模拟获取链接统计（实际项目中应该调用API）
        this.linkStats = {
          used_count: Math.floor(Math.random() * 100),
          last_used_at: new Date().toISOString()
        }
        
      } catch (error) {
        this.$message.error('生成链接失败：' + error.message)
      }
    },
    
    resetLinkForm() {
      this.linkForm = {
        landingType: 'unified',
        customParams: '',
        channel: ''
      }
      this.generatedLink = ''
      this.linkStats = null
    },
    
    copyLink(link = null) {
      const text = link || this.generatedLink
      if (!text) {
        this.$message.warning('没有可复制的链接')
        return
      }
      
      navigator.clipboard.writeText(text).then(() => {
        this.$message.success('链接已复制到剪贴板')
      }).catch(() => {
        // 降级方案
        const textarea = document.createElement('textarea')
        textarea.value = text
        document.body.appendChild(textarea)
        textarea.select()
        document.execCommand('copy')
        document.body.removeChild(textarea)
        this.$message.success('链接已复制到剪贴板')
      })
    },
    
    previewLink() {
      if (!this.generatedLink) {
        this.$message.warning('请先生成链接')
        return
      }
      window.open(this.generatedLink, '_blank')
    },
    
    testLink() {
      if (!this.generatedLink) {
        this.$message.warning('请先生成链接')
        return
      }
      // 跳转到测试页面并传递链接
      this.$router.push({
        path: '/console/test',
        query: { 
          id: this.appId,
          testLink: this.generatedLink
        }
      })
    },
    
    removeRecentLink(index) {
      this.recentLinks.splice(index, 1)
      localStorage.setItem(`recent_links_${this.appId}`, JSON.stringify(this.recentLinks))
    },
    
    clearRecentLinks() {
      this.$confirm('确定要清空最近生成的链接吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.recentLinks = []
        localStorage.removeItem(`recent_links_${this.appId}`)
        this.$message.success('已清空最近生成的链接')
      }).catch(() => {})
    },
    
    // 导航方法
    goBack() {
      this.$router.push('/console')
    },
    
    goToStats() {
      this.$router.push({ path: '/console/stats', query: { id: this.appId } })
    },
    
    goToTest() {
      this.$router.push({ path: '/console/test', query: { id: this.appId } })
    },
    
    goToConfig() {
      this.$router.push({ path: '/console/update', query: { id: this.appId } })
    },
    
    editApp() {
      this.$router.push({ path: '/console/update', query: { id: this.appId } })
    },
    
    showApiKey() {
      this.$alert(`APP Key: ${this.appInfo.appkey}<br>APP Secret: ${this.appInfo.appsecret || '请查看应用配置'}`, 'API密钥', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定'
      })
    },
    
    exportData() {
      this.showExportDialog = true
    },
    
    refreshData() {
      this.loadAppDetail()
      this.$message.success('数据已刷新')
    },
    
    // 工具方法
    formatDate(date) {
      return formatDate(date)
    },
    
    getStatusType(status) {
      const statusMap = {
        'active': 'success',
        'paused': 'warning',
        'expired': 'danger'
      }
      return statusMap[status] || 'info'
    },
    
    getStatusText(status) {
      const statusMap = {
        'active': '运行中',
        'paused': '已暂停',
        'expired': '已过期'
      }
      return statusMap[status] || '未知'
    },
    
    getPlatformText(platform) {
      const platformMap = {
        'android': 'Android',
        'ios': 'iOS',
        'both': 'Android + iOS'
      }
      return platformMap[platform] || '未设置'
    }
  }
}
</script>

<style scoped>
.app-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.app-info-card,
.link-generator-card,
.quick-actions-card,
.recent-links-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.generated-link-section {
  margin-top: 20px;
}

.link-result {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
}

.link-label {
  font-weight: 600;
  color: #303133;
  min-width: 120px;
}

.link-display {
  flex: 1;
}

.link-stats {
  margin-top: 15px;
}

.quick-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.link-text {
  color: #409EFF;
  text-decoration: none;
}

.link-text:hover {
  text-decoration: underline;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .link-result {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .quick-actions {
    justify-content: center;
  }
}
</style>